package cn.hdu.goods.user.dao;

import cn.hdu.goods.user.domain.User;
import cn.itcast.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

/**
 * 用户模块持久层
 *
 * @author qdmmy6
 */
public class UserDao {
    private QueryRunner qr = new TxQueryRunner();

    public void add(User user) throws SQLException {
        String sql = "insert into t_user(uid, loginname, loginpass, email, status, activationCode) " +
                "values (?,?,?,?,?,?);";
        Object[] params = {user.getUid(), user.getLoginname(),
                user.getLoginpass(), user.getEmail(),
                user.isStatus(), user.getActivationCode()};
        qr.update(sql, params);
    }

    public void updateStatus(String uid , boolean status) throws SQLException {
        String sql = "UPDATE t_user SET status=? WHERE uid=?";
        qr.update(sql, status, uid);
    }

    public User findByCode(String activationCode) throws SQLException {
        String sql = "SELECT * FROM t_user WHERE activationCode=?";
        return qr.query(sql, new BeanHandler<>(User.class),activationCode);
    }

    public User findByNameAndPasswd(String loginname, String loginpass) throws SQLException {
        String sql = "SELECT * FROM t_user WHERE loginname=? AND loginpass=?";
        return qr.query(sql, new BeanHandler<>(User.class), loginname, loginpass);
    }

    public boolean findByUidAndPasswd(String uid, String loginpass) throws SQLException {
        String sql = "select count(*) from t_user where uid=? AND loginpass=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), uid, loginpass);
        return number.intValue()>0;
    }

    public void updatePassword(String uid , String password) throws SQLException {
        String sql = "UPDATE t_user SET loginpass=? WHERE uid=?";
        qr.update(sql, password, uid);
    }


    /**
     * 校验用户名是否注册
     *
     * @param loginname
     * @return
     */
    public boolean ajaxValidateLoginname(String loginname) throws SQLException {
        String sql = "select count(1) from t_user where loginname=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), loginname);
        return number.intValue() == 0;
    }

    /**
     * 校验Email是否注册
     *
     * @param email
     * @return
     */
    public boolean ajaxValidateEmail(String email) throws SQLException {
        String sql = "select count(1) from t_user where email=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), email);
        return number.intValue() == 0;
    }

}
